package practise.client;

import com.google.api.gwt.oauth2.client.Auth;
import com.google.api.gwt.oauth2.client.AuthRequest;
import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootLayoutPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GWTOauthTest implements EntryPoint {
	public void onModuleLoad() {
		final FlowPanel flowPanel = new FlowPanel();
		RootLayoutPanel.get().add(flowPanel);			
		
		final String AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
		final String CLIENT_ID = "624158567149.apps.googleusercontent.com";
		final String SCOPE = "https://www.googleapis.com/auth/userinfo.email";
		
		Button login = new Button("Authenticate with google");
		login.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				final AuthRequest req = new AuthRequest(AUTH_URL, CLIENT_ID)
				.withScopes(SCOPE);
				
				final Auth AUTH = Auth.get();
							
				AUTH.login(req, new Callback<String, Throwable>() {
				
					@Override
					public void onSuccess(String result) {
						flowPanel.add(new HTML("got oauth token: " + result + 
								". token expires in " + AUTH.expiresIn(req)/1000/60 + " minutes"));				
					}
					
					@Override	
					public void onFailure(Throwable reason) {
						flowPanel.add(new HTML("authorization failure"));
						
					}
				});			
			}
		});
		
		Button logout = new Button("Clear stored tokens");
		logout.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				Auth.get().clearAllTokens();
				flowPanel.add(new HTML("all tokens cleared"));
			}
		});
		
		Button getUser = new Button("Get logged in user");
		
		flowPanel.add(login);
		flowPanel.add(logout);						
	}	
}
